<template>
    <div class="page-pd">
        <el-tabs v-model="action" @input="changeData">
            <el-tab-pane label="新增标签" name="addTag"></el-tab-pane>
            <el-tab-pane label="新增模板(模块)" name="addTemplate"></el-tab-pane>
            <el-tab-pane label="修改模板(模块)" name="modifyTemplate"></el-tab-pane>
            <el-tab-pane label="新增页面(布局)" name="addPage">
                <el-button @click="syncForm" type="primary">同步Metadata</el-button>
            </el-tab-pane>
            <el-tab-pane label="修改页面(布局)" name="modifyPage"></el-tab-pane>
            <el-tab-pane label="修改元数据" name="modifyMetadata"></el-tab-pane>
        </el-tabs>
        <el-form label-width="120px" size="small">
            <el-form-item label="appId:">
                <el-select v-model="formData.appId" @change="changeForm">
                    <el-option v-for="{appId,name} in scenes" :key="appId" :value="appId" :label="name">
                    </el-option>
                </el-select>
                <el-input v-model="formData.appId" @change="changeForm" style="width:200px">
                </el-input>
            </el-form-item>
            <el-form-item label="spId:">
                <el-input v-model="formData.spId" @change="changeForm"></el-input>
            </el-form-item>
            <el-form-item label="businessType:">
                <el-input v-model="formData.businessType" @change="changeForm"></el-input>
            </el-form-item>
            <el-form-item label="模板:">
                <el-radio-group v-model="formData.formName" v-if="action=='addTemplate'" @change="changeData">
                    <el-radio v-for="cls in FormNames" :key="cls" :label="cls">{{cls}}
                    </el-radio>
                </el-radio-group>
                <template v-else>
                    <el-select v-model="formData.formName" @change="setTemplate">
                        <el-option value=""></el-option>
                        <el-option v-for="tpl in templates" :key="tpl.formName" :value="tpl.formName" :label="tpl.name">
                        </el-option>
                    </el-select>
                    {{curTemplate && curTemplate.id}}
                    <el-button @click="loadTemplates" type="primary" size="small">刷新</el-button>

                    <el-select v-model="curPageId" @change="setPage" v-if="curTemplate && action==='modifyPage'"
                               placeholder="请选择页面">
                        <el-option value=""></el-option>
                        <el-option v-for="(pg, index) in curTemplate.pages" :key="pg.id + index" :value="pg.id"
                                   :label="pg.pageType+ '-' +pg.name">
                        </el-option>
                    </el-select>
                    {{curPageId}}

                </template>
            </el-form-item>
            <el-form-item label="提交数据:">
                <vue-json-editor v-model="dataPars" style="height:500px" :autoExpand="true"></vue-json-editor>
                <!--<textarea-auto-height v-model="dataPars" rows="10"></textarea-auto-height>-->
            </el-form-item>
        </el-form>
        <div class="t-center">
            <el-button @click="saveCfg" type="primary">提交</el-button>
        </div>
        <!--<debug-info :info="dataPars"></debug-info>-->
    </div>
</template>

<script>
import { PageTypes, FormNames } from '../common/const';
import * as api from '../common/api';
import vueJsonEditor from '../components/vueJsonEditor/vueJsonEditor';

export default {
    props: {},
    data() {
        return {
            dataPars: null,
            scenes: [
                { name: '单位', appId: 741 },
                { name: '党组织', appId: 10645 },
                { name: '老干部', appId: 743 },
                { name: '党员', appId: 10643 },
                { name: '工作人员', appId: 10639 },
            ],
            formData: {
                formName: '',
                spId: this.$x.tokenUtil.spId,
                appId: this.$x.tokenUtil.appId,
                businessType: this.$x.tokenUtil.businessType,
            },
            PageTypes,
            FormNames,

            templates: [],
            curTemplate: null,
            curPageId: '',
            action: 'modifyPage',
            appFormNames: [],
        };
    },
    created() {
        this.loadScenes()
        this.loadTemplates()
        this.changeForm();
        this.initPars()
    },
    methods: {
        loadScenes() {
            var cfg = { byHeaders: { token: this.$x.tokenUtil.token } }
            var pars = {
                businessType: this.formData.businessType,
                spId: this.spId,
                terminal: 0
            }
            this.$x.post('{abosEp}/portal/querySpMenus', pars, cfg).then(res => {
                var list = (res.data && res.data.menuList) || []
                var scenes = []
                list.filter(t => t.parentId && /orginfo.+\/list/.test(t.url)).map(m => {
                    var match = m.url && m.url.match(/moduleId=(\w+)/)
                    m.moduleId = match && match[1]
                    scenes.push(m)
                })
                this.scenes = scenes
            })
        },
        loadTemplates() {
            this.$x.post('/form/model/qry', { params: {} }).then(res => {
                this.templates = res.data || []
                this.setTemplate()
            })
        },
        loadUI() {
            this.$x.post('').then(res => {
                this.fieldList = res.data || []
            })
        },
        changeForm() {
            this.$x.tokenUtil.appId = this.formData.appId
            this.formData.formName = '';
            Promise.all([api.getOrgConfig(), api.getMemberConfig()]).then(res => {
                this.appFormNames = res.filter(r => r.data).map(r => r.data.formName)
                this.formData.formName = this.appFormNames[0] || ''
                this.setTemplate()
            })
        },
        saveCfg() {
            let pars = this.dataPars
            var call
            if (this.action === 'addTemplate') {
                call = this.$x.post('/form/model', pars)
            } else if (this.action === 'modifyTemplate') {
                pars = {
                    id: this.curTemplate.id,
                    ...pars
                }
                call = api.modifyTpl(this.curTemplate.id, pars)
            } else if (this.action === 'addPage') {
                pars = {
                    id: this.curTemplate.id,
                    ...pars
                }
                this.dataMap.addPage = pars
                if (this.curTemplate.pages.find(pg => {
                    return pars.pages.find(addPg => pg.pageType === addPg.pageType)
                })) {
                    return this.$x.toast.warning('pageType重复')
                }
                call = api.addPage(this.curTemplate.id, pars.id, pars)
            } else if (this.action === 'modifyPage') {
                pars = {
                    id: this.curPageId,
                    formId: this.curTemplate.id,
                    ...pars
                }
                call = api.modifyPage(this.curTemplate.id, this.curPageId, pars)
            } else if (this.action === 'modifyMetadata') {
                call = api.modifyMeta(this.curTemplate.id, pars)
            } else if (this.action === 'addTag') {
                call = this.$x.post('/org/tag/add', pars)
            }
            call.then(res => {
                this.$x.toast.success('保存成功')
            })
        },
        syncForm() {
            var layout = Object.entries(this.curTemplate.metadatas.properties).map(parseFieldConfig)
            let addPage = this.dataPars
            addPage.pages[0].ui = { layout }
            this.dataPars = addPage
        },
        setTemplate() {
            var curTemplate = this.templates.find(tpl => tpl.formName === this.formData.formName)
            // this.formData.appId = this.scenes[this.formData.formName]
            if (curTemplate) {
                var pars = {
                    appId: this.formData.appId,
                    businessType: this.formData.businessType,
                    spId: this.formData.spId,
                    id: curTemplate.id
                }
                this.$x.post('/form/model/page/qry', pars).then(res => {
                    this.curTemplate = res.data
                    if (this.curTemplate) {
                        if (!this.curTemplate.pages) this.curTemplate.pages = [{ ui: {} }]

                        this.dataMap.modifyTemplate = { ...this.curTemplate, metadatas: undefined, pages: undefined }

                        this.dataMap.modifyPage = this.curTemplate.pages[0]
                        this.curPageId = this.dataMap.modifyPage.id

                        this.dataMap.modifyMetadata = this.curTemplate.metadatas
                    }
                    this.setPage()
                    this.changeData()
                })
            }
        },
        setPage() {
            if (this.curTemplate) {
                var curPage = this.curTemplate.pages.find(pg => pg.id === this.curPageId)
                if (curPage) {
                    this.dataMap.modifyPage = curPage
                }
                this.changeData()
            }
        },
        changeData() {
            this.dataMap.addTemplate.formName = this.formData.formName

            this.dataMap.addTemplate.pages[0].ui.formName = this.formData.formName
            this.dataMap.addTemplate.pages[0].ui.gridCols = this.getDefaultCols(this.formData.formName)
            //this.dataMap.addPage.pages[0].ui.formName = this.formData.formName
            //this.dataMap.addTemplate.pages[0].appId = this.formData.appId

            this.dataMap.addTemplate.pages[0].type = this.formData.formName.slice(0, 3) === 'Org' ? 'Org' : 'Member'
            this.dataMap.addPage.pages[0].type = this.formData.formName.slice(0, 3) === 'Org' ? 'Org' : 'Member'

            if (this.curTemplate) {
                this.dataMap.addPage.id = this.curTemplate.id
            }

            this.dataMap.addTag = {
                businessType: this.formData.businessType,
                spId: this.formData.spId,
                name: '',
                tagType: 3, //1.系统标签，2.自定义标签，3.组织类型，4.人员类型
            }

            this.dataPars = this.dataMap[this.action]
        },
        initPars() {
            this.dataMap = {
                addTemplate: {
                    'id': undefined,
                    'formName': this.formData.formName,
                    // 'spId': this.formData.spId,
                    // 'appId': this.formData.appId,
                    // 'businessType': this.formData.businessType,
                    'metadatas': {},
                    'name': '湖北老干部单位字段模板',
                    'pages': [
                        {
                            'id': undefined,
                            'clientType': 0,
                            'spId': this.formData.spId,
                            'appId': this.formData.appId,
                            'businessType': this.formData.businessType,
                            'name': 'OrgTable',
                            'pageType': 'Table',
                            'ui': {
                                'formName': this.formData.formName,
                                'rowActions': [
                                    'Edit',
                                    'View'
                                ],
                                'batActions': [
                                    'Import',
                                    'Export'
                                ],
                                'gridCols': this.getDefaultCols(this.formData.formName),
                                //'orderBy': 'createDate desc, id desc',
                                'pageSize': 10,
                                'pageSizes': [10, 20, 30],
                                'searchFormPageType': 'TableSearch'
                            },
                            'url': '',
                            'remark': '组织主表格',
                            'type': ''
                        }
                    ]
                },
                addPage: {
                    'id': undefined,
                    pages: [{
                        // 'spId': '0',
                        // 'appId': '0',
                        // 'businessType': '0',
                        'name': '',
                        'pageType': 'FormAdd',
                        'clientType': 0,
                        'ui': {
                            layout: []
                        },
                    }]
                },
                modifyPage: {},
                modifyMetadata: {},
            }
        },
        getDefaultCols(formName) {
            try {
                return require('../_configData/tableUIs/' + formName + '.json').gridCols
            } catch (e) {
                return []
            }
        },
    },
    computed: {},
    components: { vueJsonEditor }
}


function parseFieldConfig([name, metaProperty]) {
    if (metaProperty.enum) {
        return {
            'field': name,
            'options': metaProperty.enum.map(option => ({
                'label': option,
                'value': option
            })),
            'type': 'select',
            'title': metaProperty.title,
            'props': {
                'required': true
            },
            'validate': [
                {
                    'trigger': 'blur',
                    'message': '请选择' + metaProperty.title,
                    'required': true
                }
            ]
        }
    } else {
        return {
            'field': name,
            'type': 'input',
            'title': metaProperty.title,
            'props': {
                'placeholder': '请输入' + metaProperty.title,
                'type': 'text',
                'required': true
            },
            'validate': [
                {
                    'trigger': 'blur',
                    'message': '请输入' + metaProperty.title,
                    'required': true
                }
            ]
        }
    }
}
</script>

<style lang="scss">
    textarea {
        font-family: "Courier";
        font-size: 13px;
    }
</style>
